//
//  UIViewController+Extension.swift
//  MYSwift
//
//  Created by wangshuguan on 16/8/16.
//  Copyright © 2016年 wangshuguan. All rights reserved.
//

import UIKit
import MessageUI
import AlamofireImage
import AVKit
import Alamofire
var s_HYBFullnameKey = "s_HYBFullnameKey"
extension UIViewController:MFMailComposeViewControllerDelegate,MFMessageComposeViewControllerDelegate {
    var runningPath:String?{
        get {
            return objc_getAssociatedObject(self, &s_HYBFullnameKey) as? String
        }
        set{
            objc_setAssociatedObject(self, &s_HYBFullnameKey, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
    }
    @available(iOS 9.0, *)
    class func nib(_ nibName:String = identifier)->Self {
        return self.init(nibName: nibName, bundle: nil)
    }
    class var identifier:String{
        get{
            return NSStringFromClass(self.classForCoder()).components(separatedBy: ".").last!
        }
    }
    var simpleIdentifier:String{
        get{
            return Self.identifier.replacingOccurrences(of: "gongchengyan.", with: "").replacingOccurrences(of: "ViewController", with: "")
        }
    }
    internal convenience init(nibName:String?,barItem:UITabBarItem,title:String){
        self.init(nibName: nibName, bundle: nil)
        self.tabBarItem = barItem
        self.title = title
    }
    convenience init(hidesBottomBarWhenPushed b:Bool,nibName:String) {
        self.init(nibName: nibName,bundle:nil)
        self.hidesBottomBarWhenPushed = true
    }
    convenience init(nibName: String) {
        self.init(nibName: nibName,bundle:nil)
    }
    func changeTopConstraint() {
        edgesForExtendedLayout = []
    }
    func callTel(to tel:String,name:String?=nil) {
        if let url = URL(string:"tel://\(tel)"),UIApplication.shared.canOpenURL(url) {
            if let n = name{
                UIAlertController.alertMessage("是否拨打给\(n)",btnTitles: ["拨打","取消"],action:{t in
                    if t==0{
                        if #available(iOS 10.0, *) {
                            UIApplication.shared.open(url, options: [:], completionHandler: nil)
                        } else {
                            // Fallback on earlier versions
                            UIApplication.shared.openURL(url)
                        }
                    }
                })
            }else{
                if #available(iOS 10.0, *) {
                    UIApplication.shared.open(url, options: [:], completionHandler: nil)
                } else {
                    // Fallback on earlier versions
                    UIApplication.shared.openURL(url)
                }
            }
        }else{
            UIAlertController.alertMessage("设备不支持拨打给\(tel)")
        }
    }
    func email(to email:String) {
        if !MFMailComposeViewController.canSendMail(){
            UIPasteboard.general.string = email
            UIAlertController.alertMessage("设备不支持发邮件给\(email)，已经将邮箱地址复制进粘贴板")
            return
        }
        let composeVC = MFMailComposeViewController()
        composeVC.mailComposeDelegate = self
        composeVC.setToRecipients([email])
        composeVC.modalPresentationStyle = .fullScreen
        self.present(composeVC, animated: true, completion: nil)
    }
    func sms(to recipient:String?,with text:String?) {
        self.sms(to: [recipient ?? ""], with: text)
    }
    func sms(to recipients:[String],with text:String?) {
        if MFMessageComposeViewController.canSendText(){
            let vc = MFMessageComposeViewController()
            if let t = text{
                vc.body = t
            }
            vc.recipients = recipients.filter({$0.isNumber})
            vc.messageComposeDelegate = self
            vc.modalPresentationStyle = .fullScreen
            self.navigationController?.present(vc, animated: true, completion: nil)
        }else{
            UIAlertController.alertMessage("你的设备不支持发短信")
        }
    }
    public func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true, completion: nil)
    }
    public func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
        controller.dismiss(animated: true, completion: nil)
    }
    func playMovie(urlString:String) {
        if let url = URL(string: urlString){
            let player = AVPlayer(url: url)
            let vc = AVPlayerViewController()
            vc.player = player
            vc.showsPlaybackControls = true
            vc.player?.play()
            vc.modalPresentationStyle = .fullScreen
            self.present(vc, animated: true, completion: nil)
        }else{
            UIAlertController.alertMessage("url错误，无法播放")
        }
    }
}
var k_refreshViewKey = "k_refreshViewKey"
extension UIViewController{
    var refreshView:UIActivityIndicatorView?{
        get {
            return objc_getAssociatedObject(self, &k_refreshViewKey) as? UIActivityIndicatorView
        }
        set{
            objc_setAssociatedObject(self, &k_refreshViewKey, newValue, .OBJC_ASSOCIATION_RETAIN)
        }
    }
    func showRefreshView() {
        if self.refreshView == nil {
            let parentView = UIView()
            parentView.backgroundColor = .white
            let label = UILabel()
            label.text = "正在加载中"
            if #available(iOS 13.0, *) {
            self.refreshView = UIActivityIndicatorView(style: UIActivityIndicatorView.Style.large)
            } else {
                // Fallback on earlier versions
                self.refreshView = UIActivityIndicatorView(style: .whiteLarge)
            }
            self.refreshView?.color = .green
            parentView.addSubview(self.refreshView!)
            parentView.addSubview(label)
            self.view.addSubview(parentView)
            self.refreshView?.translatesAutoresizingMaskIntoConstraints = false
            parentView.translatesAutoresizingMaskIntoConstraints = false
            label.translatesAutoresizingMaskIntoConstraints = false
            self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-[view]-|", options: .init(rawValue: 0), metrics: nil, views: ["view":parentView]))
            self.view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-[view]-|", options: .init(rawValue: 0), metrics: nil, views: ["view":parentView]))
            parentView.addConstraint(NSLayoutConstraint(item: self.refreshView!, attribute: .centerX, relatedBy: .equal, toItem: parentView, attribute: .centerX, multiplier: 1, constant: 0))
            parentView.addConstraint(NSLayoutConstraint(item: self.refreshView!, attribute: .centerY, relatedBy: .equal, toItem: parentView, attribute: .centerY, multiplier: 1, constant: 0))
            parentView.addConstraint(NSLayoutConstraint(item: label, attribute: .top, relatedBy: .equal, toItem: self.refreshView!, attribute: .bottom, multiplier: 1, constant: 0))
            parentView.addConstraint(NSLayoutConstraint(item: label, attribute: .centerX, relatedBy: .equal, toItem: parentView, attribute: .centerX, multiplier: 1, constant: 0))
            
        }
        self.refreshView?.startAnimating()
        self.refreshView?.superview?.isHidden = false
    }
    func hideRefreshView() {
        if self.refreshView != nil {
            self.refreshView?.stopAnimating()
            self.refreshView?.superview?.isHidden = true
        }
    }
    @IBAction func goBack() {
        self.navigationController?.popVC()
    }
}
extension UINavigationController{
    @objc func popViewController(count:Int = -1,animated:Bool = true) {
        guard self.viewControllers.count+count-1>=0,count<0 else {
            ZWTPrint("溢出错误的count:"+"\(self.viewControllers.count+count-1)")
            return
        }
        let vc = self.viewControllers[self.viewControllers.count+count-1]
        self.popToViewController(vc, animated: animated)
    }
    @objc func popVC() {
        self.popViewController(count: -1, animated: true)
    }
    @objc func popVCTo(vcName:String) {
        if let index = self.viewControllers.firstIndex(where: {$0.nibName == vcName}) {
            popViewController(count: index - self.viewControllers.count + 1, animated: true)
        }else{
            self.popViewController(count: -1, animated: true)
        }
    }
    @objc func popToRootViewController(_ animated:Bool = true) {
        self.popToViewController(self.viewControllers.first!, animated: animated)
    }
}
